package com.naiterui.ehp.bs.pc.common.utils;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.util.Assert;

public class ConfigUtil implements EnvironmentPostProcessor {

    private static Binder binder;

    private static ConfigurableEnvironment environment;

    public static String getString(String key) {
        Assert.notNull(environment, "environment 还未初始化！");
        return environment.getProperty(key, String.class, "");
    }

    public static <T> T bindProperties(String prefix, Class<T> clazz) {
        Assert.notNull(prefix, "prefix 不能为空");
        Assert.notNull(clazz, "class 不能为空");
        BindResult<T> result = ConfigUtil.binder.bind(prefix, clazz);
        return result.isBound() ? result.get() : null;
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        for (PropertySource<?> propertySource : environment.getPropertySources()) {
            if (propertySource.getName().equals("refreshArgs")) {
                return;
            }
        }
        ConfigUtil.environment = environment;
        ConfigUtil.binder = Binder.get(environment);
    }
}
